﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using SAM.Framework.UserBrowser;
using System.Threading.Tasks;

namespace SAM.Framework.CefSharp.UI
{
    public partial class UserWebBrowser : UserControl,IUserBrowser
    {
        public ChromiumWebBrowser browser { get; private set; }

        public object OriginBrowser => this.browser;

        private delegate void InvokeDeleagate();

        public UserWebBrowser(string url = null)
        {
            InitializeComponent();
            CefSettings cefSettings = new CefSettings();
            Cef.Initialize(cefSettings);
            this.browser = new ChromiumWebBrowser(url != null ? url : string.Empty);
            this.browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged1;
            this.browser.FrameLoadEnd += Browser_FrameLoadEnd;
            this.Controls.Add(this.browser);
            this.browser.Dock = DockStyle.Fill; 
        }

        private void Browser_IsBrowserInitializedChanged1(object sender, IsBrowserInitializedChangedEventArgs e)
        {
            if (e.IsBrowserInitialized)
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new InvokeDeleagate(RefreshWebBrowser));
                }
            }
        }
        private void RefreshWebBrowser()
        {
            this.browser.Refresh();
        }

        public event EventHandler OnFrameLoadEnd;

        private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            OnFrameLoadEnd?.Invoke(this, null);
        }

        private void Browser_IsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs e)
        {
            if (e.IsBrowserInitialized)
            {
                var mainFrame = this.browser.GetMainFrame();
            }
        }

        void IUserBrowser.Load(string url)
        {
            this.browser.Load(url);
        }

        public void ExecuteJavaScriptAsync(string code, string scriptUrl = "about:blank", int startLine = 0)
        {
            this.browser.GetMainFrame().ExecuteJavaScriptAsync(code, scriptUrl, startLine);
        }

        public void RegisterObject(string name, TransportObject transportObject)
        {
            this.browser.RegisterJsObject(name, transportObject);
        }
    }
}
